﻿using DAL;
using RabbitMQ.Client;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.Json;

namespace MQTools
{
    public class MQSender
    {

        public ConnectionFactory ConnectionFactory { get; private set; }

        public string Exchange { get; private set; }
        public string ExchangeType { get; private set; }
        public string HostName { get; private set; }
        public string VirtualHost { get; private set; }
        public string UserName { get; private set; }
        public string PassWord { get; private set; }

        public MQSender(string  hostName,string virtualHost,string userName,string password,string exchange,string exchangeType)
        {
            this.HostName = hostName;
            this.VirtualHost = virtualHost;
            this.UserName = userName;
            this.PassWord = password;
            this.Exchange = exchange;
            this.ExchangeType = exchangeType;
            ConnectionFactory = new ConnectionFactory()
            {

                VirtualHost = this.VirtualHost,
                UserName = this.UserName,
                Password = this.PassWord,
                HostName = this.HostName
            };
        }


        public void SendMessage(object message,string routeKey)
        {
            using (IConnection conn = ConnectionFactory.CreateConnection())
            using (IModel channel = conn.CreateModel())
            {
                //channel.QueueDeclare(queue:"mymessage",durable:false, exclusive:false,autoDelete:false,arguments:null);
                string trans = JsonSerializer.Serialize(message) ;
    
                channel.ExchangeDeclare(exchange: Exchange, type: ExchangeType, durable: true, autoDelete: false, arguments: null);
                //Console.WriteLine("输入需要传输的消息，输入Exit退出");
                //var message = Console.ReadLine();
                channel.BasicPublish(exchange: Exchange, routingKey: routeKey, basicProperties: null, body: Encoding.UTF8.GetBytes(trans));
            }
        }


      
    }
}